#!/usr/bin/env python
# -*- coding:utf-8 -*-

"""query tickets on 12306

Usage:
    tickets [-gdtkz] <from> <to> <date>

Options:
    -h, --help  this usage
    -g          高铁
    -d          动车
    -t          特快
    -k          快速
    -z          直达

Example:
    tickets -dg 北京 广州 2016-12-19
"""
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

from docopt import docopt
from stations import stations
from model import TrainsCollection
import parse_station

# INIT = 'https://kyfw.12306.cn/otn/leftTicket/init'
INIT = 'https://kyfw.12306.cn/otn/leftTicket/log'
REQUEST_FORMAT = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes={}'# v1.8999


def cli():
    """command-line interface"""
    arguments = docopt(__doc__)
    # print(arguments)
    try:
        from_station = stations.get(arguments['<from>'].decode('utf-8'))
        to_station = stations.get(arguments['<to>'].decode('utf-8'))
    except UnicodeDecodeError:
        from_station = stations.get(arguments['<from>'].decode('gbk'))
        to_station = stations.get(arguments['<to>'].decode('gbk'))
    date = arguments['<date>']
    url = REQUEST_FORMAT.format(date, from_station, to_station, 'ADULT')

    # verify=False不验证证书
    requests.get(INIT, verify=False) # 初始化
    print(url)
    r = requests.get(url, verify=False)
    # print(r.json())
    try:
        available_trains = r.json()['data']
        options = ''.join([key for key, value in arguments.items() if value is True])
        TrainsCollection(available_trains, options).pretty_print()
    except:
        import os
        with open("error.html", 'w') as err:
            err.write(r.content)
            print("Some error has happened! header code is %d" % r.status_code)
            print("Open %s to see response" % os.path.realpath(err.name))

def updateIfNeeded():
    # todo determine last update date and decide whether to update stations
    parse_station.doUpdate()

if __name__=='__main__':
    cli()
